#!coding:utf8
# vim: tabstop=4 shiftwidth=4 softtabstop=4
'''
Created on Aug 7, 2012

@author: join
'''
from django.shortcuts import render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
import logging

import json

LOG = logging.getLogger(__name__)
NETWORK_BYTE_TO_MB = 1024.0*1024


def render(func):
    def _render(req, *args, **argskeys):
        result = func(req, *args, **argskeys)
        #if result is redirect,do not need wrap
        if isinstance(result,HttpResponseRedirect):
            return result
        if isinstance(result,HttpResponse):
            raise Exception('function must be return tuple or list,not a httpresponse')
        
        if isinstance(result,tuple) or isinstance(result,list):
            if len(result)>1:
                template,values = result
            else:
                template,values = result[0],{}
        else:
            template,values = result,{}
            
        return render_to_response(template,values,context_instance=RequestContext(req))
    return _render


def ajaxrender(func):
    def _render(req, *args, **argskeys):
        result = func(req, *args, **argskeys)
        if isinstance(result,HttpResponse):
            raise Exception('function must be return tuple or list,not a httpresponse')
        
        if isinstance(result,int):
            msg,status = '',result
        elif isinstance(result,tuple) or isinstance(result,list):
            msg,status = result
        else:
            msg,status = result,200
            
        if isinstance(msg, dict):
            msg = json.dumps(msg)
        
        return HttpResponse(msg,status=status)
    return _render


def getMD5Str(original_str):
    '''对str进行MD5加密'''
    
    if not original_str:
        return ''
    
    import hashlib
    
    md5 = hashlib.md5()
    md5.update(original_str)
    md5Str = md5.hexdigest()
    
    return md5Str 

def init_terminal():
    '''初始化易宝终端号与序列号参数'''
    import os
    from lottery_jx.models import SerialTerminalNumber
    
    f = open(os.path.join(os.path.dirname('.'),'terminal_serial_number.txt'))
    for line in f.readlines():
        tn,sn = line.replace('\r\n','').split('\t')
        SerialTerminalNumber.objects.create(terminal_number=tn,serial_number=sn,is_used=False)
        
if __name__ == '__main__':
    init_terminal()
    